
const cache = {}

const Native = {
  async fetchAll({
    urls,
    type = 'text', // json、text
    cacheKey,
  }) {
    const cacheData = cacheKey && cache[cacheKey]
    if (cacheData) {
      return cacheData
    }

    const promiseResults = await Promise.allSettled(
      urls.map((url) =>
        fetch(url)
          .then((res) => res[type]())
          .then((content) => {
            return { content, url }
          })
      )
    )
    const results = promiseResults
      .filter(p => p.status === 'fulfilled')
      .map(p => p.value)
    cache[cacheKey] = {
      data: results,
      timestamp: Date.now(),
    }
    return cache[cacheKey]
  },
  setStorage({
    key,
    value,
  }) {
    return chrome.storage.local.set({
      [key]: value,
    })
  },
  getStorage({
    key,
  }) {
    return chrome.storage.local.get(key)
      .then((data) => data[key])
  },
  setCache({
    key,
    value,
  }) {
    cache[key] = value
  },
  getCache({
    key
  }) {
    return cache[key]
  }
}

chrome.runtime.onMessage.addListener(async (request) => {
  const { method, data, callbackId } = request
  try {
    const result = await Native[method](data)
    chrome.runtime.sendMessage({
      success: true,
      callbackId,
      data: result,
    })
  } catch (ex) {
    chrome.runtime.sendMessage({
      success: false,
      callbackId,
      data: ex,
    })
  }
})